/*
 * axios封装
 * @Author: linzy
 * @Date: 2022-11-18
 */
import Axios from "axios";
import { notification, message } from "antd";
import store from "../index";
import createHashHistory from "history/createHashHistory";
let myHistory = createHashHistory();
const { dispatch } = store;
const axios = Axios.create({
  timeout: 60000
});
const codeMsgObj = {
  400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户没有权限（令牌、用户名、密码错误）。",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "服务器发生错误，请检查服务器。",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。"
};
/**
 * notification封装
 * @param {string} description
 * @param {string} message
 */
function notifyFun(description, message = "") {
  notification.error({
    message: "请求错误：" + message,
    description
  });
}
export default (url, options = {}) => {
  // url补斜杆/
  if (!/^\//.test(url)) {
    url = "/" + url;
  }
  options?.method === undefined && (options.method = "post");
  let {
    method,
    params,
    data,
    prefix,
    notify = true,
    notifySuccess = true,
    back,
    delay = 0,
    excel
  } = options;
  method = method.toLowerCase();
  // 处理get post传参名
  if (method === "get") {
    options.params = data || params;
  }
  // 处理 Accept
  if (/(post|put)/.test(method)) {
    options.Accept = "application/json";
    options.headers = {
      "Content-Type": "application/json; charset=utf-8",
      ...options.headers
    };
  }
  return new Promise((resolve, reject) => {
    // 处理 page
    const page = options.data?.page || options.params?.page;
    if (page && page > 100) {
      notifyFun("请求被拦截：为减少服务器压力，只支持查询100页以内的数据！");
      reject({
        code: -1,
        msg: "请求被拦截：为减少服务器压力，只支持查询100页以内的数据！"
      });
      return;
    }
    try {
      axios({
        url,
        ...options
      })
        .then(response => {
          const { status, data, config } = response;
          if (status >= 200 && status < 300) return data;
          notify && notifyFun(codeMsgObj[status], `${status}: ${config.url}`);
          reject(data);
        })
        .then(data => {
          const { code, res, msg } = data;
          if (code === 0) {
            if (res && typeof res !== "boolean") {
              resolve(res);
            } else {
              notifySuccess &&
                notify &&
                message.success((prefix || "操作") + "成功");
              resolve(data);
              setTimeout(() => {
                back && myHistory.go(-1);
              }, delay);
              excel && myHistory.push("/operation/export/list");
            }
          } else if (/^请登录/.test(msg)) {
            notify && notifyFun(msg, code);
            dispatch({
              type: "login/logout"
            });
            reject(data);
          } else {
            notify && notifyFun(msg, code);
            reject(data);
          }
        })
        .catch(err => {
          reject(err);
        });
    } catch (err) {
      reject(err);
    }
  });
};
